websocketemit('alluser', null);

var searchPage = 1;    
var pageAmount = 50;
var mData;
function InputPageAmountChanged(obj){ 
    searchPage = 1;   
    pageAmount = ~~$(obj).val();    

    SetupPagination();
    SetupList();
}
function SetupPagination() {
    new Page({
        id: 'pagination',
        pageTotal: Math.ceil(mData.length / pageAmount), //必填,总页数
        pageAmount: pageAmount,  //每页多少条
        dataTotal: mData.length, //总共多少条数据
        curPage: 1, //初始页码,不填默认为1
        pageSize: 15, //分页个数,不填默认为5
        showPageTotalFlag: true, //是否显示数据统计,不填默认不显示
        showSkipInputFlag: false, //是否支持跳转,不填默认不显示
        getPage: function (page) {
            //获取当前页数
            searchPage = page;
            SetupList();
        }
    });
}

onwebsocket('alluser', (data) => {
    mData = data;
    SetupPagination();
    SetupList();
});

function SetupList(){        
    var theme = ["","success","error","warning","info"];

    var itemTemplate = "<tr class={4}>\
                            <td>{0}</td>\
                            <td>{1}</td>\
                            <td>{2}</td> \
                            <td class=\"{7}\">{6}</td>\
                            <td><button id=\"{0}\" onclick=\"BtnActiveClick(this, {5})\">{3}</button></td>\
                        </tr>";
    var htmls = "";
    var startIndex = (searchPage - 1) * pageAmount;
    for(var i = startIndex; i < mData.length; i++){
        if(i >= startIndex + pageAmount)
            break;

        var item = mData[i];

        var stateClass = "unactive";
        var spanTxt = "禁用中";
        var btnTxt = "启用";                
        if(item.active){
            stateClass = "active";
            spanTxt = "启用中";
            btnTxt = "禁止";            
        }
        
        

        htmls += String.format(itemTemplate, item.user, item.password, item.desc, btnTxt, theme[i % 5], !item.active, spanTxt, stateClass);
    }

    document.getElementById("files").innerHTML = htmls;
}

function BtnNewAccountClick(){
    var inputAccount = $("#inputAccount").val();
    var inputProject = $("#inputProject").val();
    websocketemit('newuser', {user:inputAccount, password:"", desc:inputProject});
}
onwebsocket('newuser', (data)=>{
    if(data.result == false){
        alert(data.info);
        return;
    }

    websocketemit('alluser', null);
    $("#inputAccount").val("");
    $("#inputProject").val("");
});

function BtnActiveClick(obj, active){
    websocketemit('activeuser', {active: active,user:$(obj).attr("id")});        
}

onwebsocket('activeuser', (data)=>{
    if(data.result == false){
        alert(data.info);
        return;
    }

    websocketemit('alluser', null);
});
